# -*- coding: utf8 -*-
##############################################################
#             Copyright (C), 2009-2013, ali
#
# FileName:   SDTest.py
# Author:     yixun.zengyx
# Version:    0.1
#
# Description:
#   Status Drive Test
#
#
# Function List:
#
#
# History:
#     <Author/Maintainer>      <Date>      <Modification>
#       yixun.zengyx         2013/05/09    Create this file
#############################################################

import os
import sys
from optparse import OptionParser
from SDTReport import *
from SDTestBase import *
from Lib.Color import *
import Lib.Exception
import Lib.SendMail
import time
# from mako.template import Template
from mako.lookup import TemplateLookup
import pdb

class UnitLogger:

    @staticmethod
    def info(msg):
        Logger.Info(msg)

    @staticmethod
    def warning(msg, expectedValue='', actualValue=''):
        if expectedValue == '' and actualValue == '':
            raise Lib.Exception.WarnException(msg)
        else:
            raise Lib.Exception.WarnException("%s. expectedValue is %s, actualValue is %s" % (msg, expectedValue, actualValue))

    @staticmethod
    def error(msg):
        Logger.Error(msg)


class SDTest:
    def __init__(self,options):
        self.options = options
        if options.env==None:
            TestEnv.Env["config"] = None
        else:
            TestEnv.Env["config"] = options.env.lower()
        self.TcModuleInfo=ModuleInfo(options.configfile,options.module)
        self.TestResult = TestResult(options.prefix_resultfile,options.logfile)#通过此文件进行结果统计
        self.ASSERT = Assertion(self.TestResult)
        if (options.drive.lower()<>"show") and (options.drive.lower()<>"report"):
            self.TestResult.init()
        self.Runner = SDTRunner(self.TestResult,self.ASSERT)
        
    def parseConfig(self):
        pass

                
    def notCompleted(self):
        for mname in self.TcModuleInfo.getModuleList():
            print_colorful('yellow', True, "Module Name:["+mname+"]")
            
    def show(self):
        self.Runner.Load(self.TcModuleInfo,self.options.classname,self.options.tcnames)
        self.Runner.Count(options.group)
        self.TcModuleInfo=ModuleInfo(options.configfile,options.module)
        self.Runner.Load(self.TcModuleInfo,self.options.classname,self.options.tcnames)
        self.Runner.Show(options.group,True)
        
    def run(self):
        m = self.TcModuleInfo
        c = self.options.classname
        tc = self.options.tcnames
        self.Runner.Load(self.TcModuleInfo,self.options.classname,self.options.tcnames)
        self.Runner.Count(options.group)
        self.TcModuleInfo=ModuleInfo(options.configfile,options.module)
#         self.TestResult.Info("The Total of TestCase:<"+str(self.Runner.tctotal)+">",True)
        self.TestResult.Info("start time:<"+str(time.time())+">",True)
        self.Runner.Load(self.TcModuleInfo,self.options.classname,self.options.tcnames)
        self.Runner.Run(options.group,self.options.drive.lower())
        self.TestResult.Info("terminal time:<"+str(time.time())+">",True)
        self.TestResult.Close()
        
        
    def go(self):
        if self.options.drive.lower()=="show":
            self.show()
            return
        if self.options.drive.lower()=="report":
            self.report()
            return
        self.run()
        if self.options.read_resultfile <> None:
            self.report()
            
            
    def sendmail(self,title,reportfile):
        if self.options.read_resultfile ==None:
            return
        if self.options.sendmail.lower()<>"on":
            return
        fd = open(reportfile,"rb")
        isOk = True
        try:
            fd.seek(0)
            filebody = fd.read().decode("utf-8")
        except:
            isOk = False
        finally:
            fd.close()
        if not isOk:
            return
        isOk = True
        try:
            recipent_list = HandleData.parserPackage(self.options.sendmailconfig)
            attache_list = []
            if self.options.attache<>None:
                attache_list = self.options.attache.split(",")
        except:
            isOk = False
        if isOk:
            Lib.SendMail.sendMail(title=title, recipent_list=recipent_list,html=filebody, attache_list=attache_list)
            
            
    def report(self):
        tcsummary = HandleData.parserTestResult(options.read_resultfile.split(","))
        default_color = "black"
        error_color = "red"
        color_fail = default_color
        color_error = default_color
        color_state = default_color
        
        if tcsummary["fail"]>0 or tcsummary["error"]>0:
            color_state = error_color
        if tcsummary["fail"]>0:
            color_fail=error_color
        if tcsummary["error"]>0:
            color_error = error_color

        strTime = time.strftime('%Y%m%d%H%M%S')
        title = "%s  %s"%(options.project,strTime)
        wfilename = "%s_%s.%s"%("tcsummary",strTime,"htm")
        
        mylookup = TemplateLookup(directories=['./template'], input_encoding='utf-8',output_encoding='utf-8', encoding_errors='replace')
        mytemplate = mylookup.get_template("tcsummary.tl")
        write_repot_string = mytemplate.render(title=title.decode("UTF8"),duration=str(tcsummary["duration"]).decode("UTF8"),state=tcsummary["state"].decode("UTF8"),
                                tcsvn=options.svn.decode("UTF8"),color_state=color_state,
                                color_fail=color_fail,color_error=color_error,
                                tctotal=str(tcsummary["tctotal"]).decode("UTF8"),rate=tcsummary["rate"].decode("UTF8"),
                                                passtotal=str(tcsummary["success"]).decode("UTF8"),failtotal=str(tcsummary["fail"]).decode("UTF8"),
                                                errortotal=str(tcsummary["error"]).decode("UTF8"))
        repotFileName = "./report/"+wfilename
        self.TestResult.Write(write_repot_string,repotFileName)
        print_colorful('yellow',True, "tcsummary output : %s"%(repotFileName))
        self.sendmail(title,repotFileName)

if __name__=='__main__':
#     import sys
#     print sys.getdefaultencoding()
    parser = OptionParser()
    parser.add_option("-i", "--import", dest="configfile", help="import test case module!", default = None)
    parser.add_option("-l", "--log", dest="logfile", help="SDTest Detail log file!default is None = stdout", default = None)
    parser.add_option("-d", "--drive", dest="drive", help="drive mode:show/run/debug/report", default="run")
    parser.add_option("-r", "--rreport", dest="read_resultfile", help="generation tcsummary with result logfile list", default=None)
    parser.add_option("-p", "--project", dest="project", help="project name", default="")
    parser.add_option("-s", "--sendmail", dest="sendmail", help="sendmail: on or off,default is off", default="off")
    parser.add_option("-e", "--sendmailconfig", dest="sendmailconfig", help="sendmail: read mail list file, default:./config/mail.conf", default="./config/mail.conf")
    parser.add_option("-a", "--mailattache",dest="attache", help="sendmail: attache file list",default=None)
    parser.add_option("-b", "--svn_address", dest="svn", help="svn address", default="")
    parser.add_option("-w", "--wreport", dest="prefix_resultfile", help="output result logfile", default="./log/result.log")
    parser.add_option("-g", "--group", dest="group", help="Based on the group name to test", default=None)
    parser.add_option("-m", "--module", dest="module", help="Test Module", default=None)
    parser.add_option("-c", "--class", dest="classname", help="Test Class", default=None)
    parser.add_option("-t", "--testcase", dest="tcnames", help="TestCase", default=None)
    parser.add_option("-v", "--env", dest="env", help="Env", default=None)
    (options, args) = parser.parse_args()
    if len(sys.argv)==1:
        parser.print_help()
        exit()
    sdtester = SDTest(options)
    sdtester.go()